package com.github.binarywang.demo.wechat.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.common.collect.Lists;
import com.google.common.io.Files;

import cn.binarywang.wx.miniapp.api.WxMaService;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.exception.WxErrorException;

@RestController
@RequestMapping({ "/wechat/media" })
public class WxMaMediaController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WxMaService service;

	@PostMapping({ "/upload" })
	public List<String> uploadMedia(HttpServletRequest request) throws WxErrorException {
		CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		if (!resolver.isMultipart(request)) {
			return Lists.newArrayList();
		}

		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> it = multiRequest.getFileNames();
		List<String> result = Lists.newArrayList();
		while (it.hasNext()) {
			try {
				MultipartFile file = multiRequest.getFile((String) it.next());
				File newFile = new File(Files.createTempDir(), file.getOriginalFilename());
				this.logger.info("filePath is ：" + newFile.toString());
				file.transferTo(newFile);
				WxMediaUploadResult uploadResult = this.service.getMediaService().uploadMedia("image", newFile);
				this.logger.info("media_id ： " + uploadResult.getMediaId());
				result.add(uploadResult.getMediaId());
			} catch (IOException e) {
				this.logger.error(e.getMessage(), e);
			}
		}

		return result;
	}

	@GetMapping({ "/download/{mediaId}" })
	public File getMedia(@PathVariable String mediaId) throws WxErrorException {
		return this.service.getMediaService().getMedia(mediaId);
	}
}
